package com.mysoft.gfyx.common.rpc.omp;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.mysoft.gfyx.common.rpc.omp.dto.GetTokenResponseDto;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.form.FormEncoder;
import feign.form.spring.SpringFormEncoder;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.HashMap;
import java.util.Map;

public class OMPClientConfiguration implements RequestInterceptor {

    protected String authHost;

    protected String clientSecret;

    public OMPClientConfiguration(String authHost, String clientSecret) {
        this.authHost = authHost;
        this.clientSecret = clientSecret;
    }

    @Override
    public void apply(RequestTemplate template) {
        // 获取Token，暂且不加缓存
        String token = getToken();
        template.header("Authorization", "Bearer " + token);
    }

    protected String getToken() {
        OMPAuthService ompAuthService = Feign.builder()
                .encoder(new FormEncoder())
                .decoder(new JacksonDecoder())
                .target(OMPAuthService.class, authHost);

        GetTokenResponseDto getTokenResponseDto = ompAuthService.getToken("client_credentials", "defaultApi", clientSecret);

        return getTokenResponseDto.getAccess_token();
    }
}